package com.mls.wms.android.util;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


public class UpdateManager {
    /* 检测版本号 */
    private static final int CHECK_FINISH_NO_UPDATE = 0;
    private static final int CHECK_FINISH_TO_UPDATE = 1;
    private static final int MEDIA_NO_MOUNTED = 2;
    /* 下载中 */
    private static final int DOWNLOAD = 3;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 4;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 文件名称 */
    private String mFileName = "wms.apk";
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Activity mActivity;
    /* 更新进度条 */
    private ProgressBar mProgress;
    /* 下载提示 */
    private Dialog mDownloadDialog;
    /* 主界面进度条 */
    private AnimDialogFragment mProgressDialog;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //检测完成
                case CHECK_FINISH_NO_UPDATE:
                    mProgressDialog.dismiss();
                    Toast.makeText(mActivity, R.string.soft_update_no, Toast.LENGTH_LONG).show();
                    break;
                case CHECK_FINISH_TO_UPDATE:
                    mProgressDialog.dismiss();
                    showNoticeDialog();
                    break;
                case MEDIA_NO_MOUNTED:
                    Toast.makeText(mActivity, R.string.soft_sdcard_no_mounted, Toast.LENGTH_LONG).show();
                    break;
                //正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Activity activity, AnimDialogFragment animDialogFragment) {
        this.mActivity = activity;
        this.mProgressDialog = animDialogFragment;
    }


    /**
     * 检测软件更新
     *
     * @return
     */
    public void checkUpdate() {
        mProgressDialog.show(mActivity.getFragmentManager(), mActivity.getClass().toString());

        // 获取当前软件版本
        final int versionCode = getVersionCode(mActivity);

        // 获取服务端版本号
        VolleyUtils.get((BaseApplication) mActivity.getApplication(), VolleyUtils.getUrl((BaseApplication) mActivity.getApplication(), ServicePort.getUrl(ServicePort.AutoUpdateGetVersion)), new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                int serviceCode = 0;
                try {
                    serviceCode = Integer.parseInt(s.replace("'", "").replace("\"", ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 版本判断
                if (serviceCode > versionCode) {
                    mHandler.sendEmptyMessage(CHECK_FINISH_TO_UPDATE);
                } else {
                    mHandler.sendEmptyMessage(CHECK_FINISH_NO_UPDATE);
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                mHandler.sendEmptyMessage(CHECK_FINISH_NO_UPDATE);
            }
        }, 1);
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo("com.mls.wms.android", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        Builder builder = new Builder(mActivity);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        // 更新
        builder.setPositiveButton(R.string.btn_text_update, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 显示下载对话框
                showDownloadDialog();
            }
        });
        // 稍后更新
        builder.setNegativeButton(R.string.btn_text_update_later, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        Builder builder = new Builder(mActivity);
        builder.setTitle(R.string.soft_updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mActivity);
        View v = inflater.inflate(R.layout.dg_progress_soft_update, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.btn_text_cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 下载文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }


    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                    mSavePath = folder.getAbsolutePath();

                    URL url = new URL(VolleyUtils.getUrl((BaseApplication) mActivity.getApplication(), ServicePort.getUrl(ServicePort.AutoUpdateGetPatch)));
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    // 判断文件目录是否存在
                    if (!folder.exists()) {
                        folder.mkdir();
                    }
                    File apkFile = new File(mSavePath, mFileName);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numRead = is.read(buf);
                        count += numRead;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numRead <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numRead);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                } else {
                    mHandler.sendEmptyMessage(MEDIA_NO_MOUNTED);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkFile = new File(mSavePath, mFileName);
        if (!apkFile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
        mActivity.startActivity(intent);
    }
}
